<template>
  <div class="exam-taking">
    <!-- 考试头部 -->
    <div class="exam-header">
      <div class="header-left">
        <div class="exam-info">
          <h2>{{ exam.title }}</h2>
          <span class="exam-meta">{{ exam.questionCount }}题 · {{ exam.duration }}分钟</span>
        </div>
      </div>
      
      <div class="header-center">
        <div class="timer" :class="{ warning: timeRemaining < 300 }">
          <el-icon><Clock /></el-icon>
          <span>{{ formatTime(timeRemaining) }}</span>
        </div>
      </div>
      
      <div class="header-right">
        <el-button @click="showSubmitDialog = true" type="primary">
          提交试卷
        </el-button>
      </div>
    </div>

    <!-- 考试内容 -->
    <div class="exam-content">
      <!-- 左侧：题目区域 -->
      <div class="question-area">
        <div class="question-header">
          <div class="question-nav">
            <el-button 
              @click="previousQuestion" 
              :disabled="currentQuestionIndex === 0"
              circle
            >
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            
            <span class="question-counter">
              {{ currentQuestionIndex + 1 }} / {{ exam.questionCount }}
            </span>
            
            <el-button 
              @click="nextQuestion" 
              :disabled="currentQuestionIndex === exam.questionCount - 1"
              circle
            >
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
          
          <div class="question-type">
            <el-tag :type="getQuestionTypeColor(currentQuestion.type)">
              {{ getQuestionTypeName(currentQuestion.type) }}
            </el-tag>
            <span class="question-score">{{ currentQuestion.score }}分</span>
          </div>
        </div>
        
        <div class="question-content">
          <div class="question-title">
            {{ currentQuestionIndex + 1 }}. {{ currentQuestion.title }}
          </div>
          
          <div v-if="currentQuestion.description" class="question-description">
            {{ currentQuestion.description }}
          </div>
          
          <div v-if="currentQuestion.code" class="question-code">
            <pre><code>{{ currentQuestion.code }}</code></pre>
          </div>
          
          <!-- 单选题 -->
          <div v-if="currentQuestion.type === 'single'" class="question-options">
            <el-radio-group v-model="answers[currentQuestion.id]">
              <div 
                v-for="(option, index) in currentQuestion.options" 
                :key="index"
                class="option-item"
              >
                <el-radio :label="option.key">{{ option.key }}. {{ option.text }}</el-radio>
              </div>
            </el-radio-group>
          </div>
          
          <!-- 多选题 -->
          <div v-if="currentQuestion.type === 'multiple'" class="question-options">
            <el-checkbox-group v-model="answers[currentQuestion.id]">
              <div 
                v-for="(option, index) in currentQuestion.options" 
                :key="index"
                class="option-item"
              >
                <el-checkbox :label="option.key">{{ option.key }}. {{ option.text }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
          
          <!-- 判断题 -->
          <div v-if="currentQuestion.type === 'judge'" class="question-options">
            <el-radio-group v-model="answers[currentQuestion.id]">
              <div class="option-item">
                <el-radio label="true">正确</el-radio>
              </div>
              <div class="option-item">
                <el-radio label="false">错误</el-radio>
              </div>
            </el-radio-group>
          </div>
          
          <!-- 填空题 -->
          <div v-if="currentQuestion.type === 'fill'" class="question-fill">
            <div 
              v-for="(blank, index) in currentQuestion.blanks" 
              :key="index"
              class="fill-item"
            >
              <label>第{{ index + 1 }}空：</label>
              <el-input 
                v-model="answers[currentQuestion.id][index]"
                placeholder="请输入答案"
              />
            </div>
          </div>
          
          <!-- 简答题 -->
          <div v-if="currentQuestion.type === 'essay'" class="question-essay">
            <el-input
              v-model="answers[currentQuestion.id]"
              type="textarea"
              :rows="8"
              placeholder="请输入你的答案..."
              show-word-limit
              :maxlength="1000"
            />
          </div>
          
          <!-- 编程题 -->
          <div v-if="currentQuestion.type === 'code'" class="question-code-editor">
            <div class="code-editor-header">
              <span>代码编辑器</span>
              <el-select v-model="codeLanguage" size="small">
                <el-option label="JavaScript" value="javascript" />
                <el-option label="Python" value="python" />
                <el-option label="Java" value="java" />
              </el-select>
            </div>
            <textarea 
              v-model="answers[currentQuestion.id]"
              class="code-textarea"
              :placeholder="getCodePlaceholder()"
            ></textarea>
            <div class="code-actions">
              <el-button @click="runCode" size="small">
                <el-icon><CaretRight /></el-icon>
                运行代码
              </el-button>
              <el-button @click="resetCode" size="small">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="question-actions">
          <el-button @click="markQuestion" :type="isMarked ? 'warning' : ''">
            <el-icon><Flag /></el-icon>
            {{ isMarked ? '取消标记' : '标记题目' }}
          </el-button>
          
          <el-button @click="clearAnswer">
            <el-icon><Delete /></el-icon>
            清空答案
          </el-button>
        </div>
      </div>
      
      <!-- 右侧：答题卡 -->
      <div class="answer-sheet">
        <div class="sheet-header">
          <h3>答题卡</h3>
          <div class="progress-info">
            <span>已答：{{ answeredCount }}/{{ exam.questionCount }}</span>
          </div>
        </div>
        
        <div class="sheet-legend">
          <div class="legend-item">
            <div class="legend-color answered"></div>
            <span>已答</span>
          </div>
          <div class="legend-item">
            <div class="legend-color marked"></div>
            <span>标记</span>
          </div>
          <div class="legend-item">
            <div class="legend-color current"></div>
            <span>当前</span>
          </div>
          <div class="legend-item">
            <div class="legend-color unanswered"></div>
            <span>未答</span>
          </div>
        </div>
        
        <div class="sheet-grid">
          <div 
            v-for="(question, index) in questions" 
            :key="question.id"
            class="sheet-item"
            :class="{
              current: index === currentQuestionIndex,
              answered: isAnswered(question.id),
              marked: markedQuestions.includes(question.id)
            }"
            @click="goToQuestion(index)"
          >
            {{ index + 1 }}
          </div>
        </div>
        
        <div class="sheet-stats">
          <div class="stat-item">
            <span class="stat-label">总题数</span>
            <span class="stat-value">{{ exam.questionCount }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">已答题</span>
            <span class="stat-value">{{ answeredCount }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">未答题</span>
            <span class="stat-value">{{ exam.questionCount - answeredCount }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">标记题</span>
            <span class="stat-value">{{ markedQuestions.length }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 提交确认对话框 -->
    <el-dialog
      v-model="showSubmitDialog"
      title="提交试卷"
      width="400px"
      :before-close="handleCloseSubmit"
    >
      <div class="submit-content">
        <div class="submit-warning">
          <el-icon><Warning /></el-icon>
          <span>确定要提交试卷吗？提交后将无法修改答案。</span>
        </div>
        
        <div class="submit-stats">
          <div class="stat-row">
            <span>总题数：</span>
            <span>{{ exam.questionCount }}题</span>
          </div>
          <div class="stat-row">
            <span>已答题：</span>
            <span>{{ answeredCount }}题</span>
          </div>
          <div class="stat-row">
            <span>未答题：</span>
            <span class="unanswered-count">{{ exam.questionCount - answeredCount }}题</span>
          </div>
          <div class="stat-row">
            <span>剩余时间：</span>
            <span>{{ formatTime(timeRemaining) }}</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showSubmitDialog = false">取消</el-button>
        <el-button type="primary" @click="submitExam" :loading="submitting">
          确定提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  Clock, ArrowLeft, ArrowRight, Flag, Delete, 
  CaretRight, Refresh, Warning
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 响应式数据
const currentQuestionIndex = ref(0)
const answers = ref({})
const markedQuestions = ref([])
const timeRemaining = ref(3600) // 60分钟
const showSubmitDialog = ref(false)
const submitting = ref(false)
const codeLanguage = ref('javascript')
const timer = ref(null)

// 模拟考试数据
const exam = ref({
  id: 1,
  title: 'JavaScript基础能力测试',
  questionCount: 50,
  duration: 60
})

const questions = ref([
  {
    id: 1,
    type: 'single',
    title: 'JavaScript中哪个关键字用于声明变量？',
    score: 2,
    options: [
      { key: 'A', text: 'var' },
      { key: 'B', text: 'let' },
      { key: 'C', text: 'const' },
      { key: 'D', text: '以上都是' }
    ]
  },
  {
    id: 2,
    type: 'multiple',
    title: 'JavaScript中的数据类型包括哪些？',
    score: 3,
    options: [
      { key: 'A', text: 'Number' },
      { key: 'B', text: 'String' },
      { key: 'C', text: 'Boolean' },
      { key: 'D', text: 'Object' }
    ]
  },
  {
    id: 3,
    type: 'judge',
    title: 'JavaScript是一种编译型语言。',
    score: 1
  },
  {
    id: 4,
    type: 'fill',
    title: '请填空：JavaScript中用于输出内容到控制台的方法是 ___，用于弹出警告框的方法是 ___。',
    score: 2,
    blanks: 2
  },
  {
    id: 5,
    type: 'essay',
    title: '请简述JavaScript中闭包的概念和作用。',
    score: 5
  }
])

// 计算属性
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value]
})

const answeredCount = computed(() => {
  return Object.keys(answers.value).filter(id => {
    const answer = answers.value[id]
    if (Array.isArray(answer)) {
      return answer.length > 0 && answer.some(a => a !== '' && a !== null && a !== undefined)
    }
    return answer !== '' && answer !== null && answer !== undefined
  }).length
})

const isMarked = computed(() => {
  return markedQuestions.value.includes(currentQuestion.value.id)
})

// 方法
const getQuestionTypeColor = (type) => {
  const colors = {
    'single': 'primary',
    'multiple': 'success',
    'judge': 'warning',
    'fill': 'info',
    'essay': 'danger',
    'code': 'purple'
  }
  return colors[type] || 'default'
}

const getQuestionTypeName = (type) => {
  const names = {
    'single': '单选题',
    'multiple': '多选题',
    'judge': '判断题',
    'fill': '填空题',
    'essay': '简答题',
    'code': '编程题'
  }
  return names[type] || '未知'
}

const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

const nextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
  }
}

const goToQuestion = (index) => {
  currentQuestionIndex.value = index
}

const isAnswered = (questionId) => {
  const answer = answers.value[questionId]
  if (Array.isArray(answer)) {
    return answer.length > 0 && answer.some(a => a !== '' && a !== null && a !== undefined)
  }
  return answer !== '' && answer !== null && answer !== undefined
}

const markQuestion = () => {
  const questionId = currentQuestion.value.id
  const index = markedQuestions.value.indexOf(questionId)
  
  if (index > -1) {
    markedQuestions.value.splice(index, 1)
  } else {
    markedQuestions.value.push(questionId)
  }
}

const clearAnswer = () => {
  const questionId = currentQuestion.value.id
  if (currentQuestion.value.type === 'fill') {
    answers.value[questionId] = new Array(currentQuestion.value.blanks).fill('')
  } else if (currentQuestion.value.type === 'multiple') {
    answers.value[questionId] = []
  } else {
    answers.value[questionId] = ''
  }
}

const getCodePlaceholder = () => {
  const placeholders = {
    'javascript': '// 请在这里编写JavaScript代码\nfunction solution() {\n    // your code here\n}',
    'python': '# 请在这里编写Python代码\ndef solution():\n    # your code here\n    pass',
    'java': '// 请在这里编写Java代码\npublic class Solution {\n    public void solution() {\n        // your code here\n    }\n}'
  }
  return placeholders[codeLanguage.value] || ''
}

const runCode = () => {
  ElMessage.info('代码运行功能开发中...')
}

const resetCode = () => {
  answers.value[currentQuestion.value.id] = getCodePlaceholder()
}

const handleCloseSubmit = () => {
  showSubmitDialog.value = false
}

const submitExam = async () => {
  submitting.value = true
  
  try {
    // 模拟提交API
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    clearInterval(timer.value)
    ElMessage.success('试卷提交成功！')
    router.push(`/exam/result/${exam.value.id}`)
  } catch (error) {
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

const startTimer = () => {
  timer.value = setInterval(() => {
    if (timeRemaining.value > 0) {
      timeRemaining.value--
    } else {
      // 时间到，自动提交
      clearInterval(timer.value)
      ElMessageBox.alert('考试时间已到，系统将自动提交试卷', '时间到', {
        confirmButtonText: '确定',
        callback: () => {
          submitExam()
        }
      })
    }
  }, 1000)
}

const initAnswers = () => {
  questions.value.forEach(question => {
    if (question.type === 'multiple') {
      answers.value[question.id] = []
    } else if (question.type === 'fill') {
      answers.value[question.id] = new Array(question.blanks).fill('')
    } else {
      answers.value[question.id] = ''
    }
  })
}

// 生命周期
onMounted(() => {
  initAnswers()
  startTimer()
  
  // 防止页面刷新
  window.addEventListener('beforeunload', (e) => {
    e.preventDefault()
    e.returnValue = '确定要离开吗？考试进度将丢失。'
  })
})

onUnmounted(() => {
  clearInterval(timer.value)
  window.removeEventListener('beforeunload', () => {})
})
</script>

<style lang="scss" scoped>
.exam-taking {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid var(--el-border-color-extra-light);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-left {
  .exam-info {
    h2 {
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 4px;
      color: var(--el-text-color-primary);
    }
    
    .exam-meta {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}

.timer {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-color-primary);
  
  &.warning {
    color: var(--el-color-danger);
    animation: pulse 1s infinite;
  }
}

.exam-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.question-area {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: white;
  margin: 16px 0 16px 16px;
  border-radius: 8px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-extra-light);
}

.question-nav {
  display: flex;
  align-items: center;
  gap: 16px;
  
  .question-counter {
    font-size: 16px;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }
}

.question-type {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .question-score {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.question-content {
  margin-bottom: 24px;
}

.question-title {
  font-size: 16px;
  font-weight: 500;
  line-height: 1.6;
  margin-bottom: 16px;
  color: var(--el-text-color-primary);
}

.question-description {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 16px;
  line-height: 1.5;
}

.question-code {
  background: var(--el-fill-color-extra-light);
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 16px;
  
  pre {
    margin: 0;
    font-family: 'Consolas', 'Monaco', monospace;
    font-size: 14px;
    line-height: 1.4;
  }
}

.question-options {
  .option-item {
    margin-bottom: 12px;
    
    :deep(.el-radio),
    :deep(.el-checkbox) {
      width: 100%;
      
      .el-radio__label,
      .el-checkbox__label {
        width: calc(100% - 30px);
        line-height: 1.5;
      }
    }
  }
}

.question-fill {
  .fill-item {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    
    label {
      min-width: 80px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
    
    .el-input {
      flex: 1;
    }
  }
}

.question-code-editor {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  overflow: hidden;
  
  .code-editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    background: var(--el-fill-color-extra-light);
    border-bottom: 1px solid var(--el-border-color-lighter);
    
    span {
      font-size: 14px;
      font-weight: 500;
    }
  }
  
  .code-textarea {
    width: 100%;
    height: 300px;
    border: none;
    padding: 12px;
    font-family: 'Consolas', 'Monaco', monospace;
    font-size: 14px;
    line-height: 1.4;
    resize: none;
    outline: none;
  }
  
  .code-actions {
    padding: 8px 12px;
    background: var(--el-fill-color-extra-light);
    border-top: 1px solid var(--el-border-color-lighter);
    display: flex;
    gap: 8px;
  }
}

.question-actions {
  display: flex;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-extra-light);
}

.answer-sheet {
  width: 280px;
  background: white;
  margin: 16px 16px 16px 0;
  border-radius: 8px;
  padding: 20px;
  overflow-y: auto;
}

.sheet-header {
  margin-bottom: 16px;
  
  h3 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 8px;
    color: var(--el-text-color-primary);
  }
  
  .progress-info {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.sheet-legend {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  margin-bottom: 16px;
  
  .legend-item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    
    .legend-color {
      width: 12px;
      height: 12px;
      border-radius: 2px;
      
      &.answered {
        background: var(--el-color-success);
      }
      
      &.marked {
        background: var(--el-color-warning);
      }
      
      &.current {
        background: var(--el-color-primary);
      }
      
      &.unanswered {
        background: var(--el-border-color-light);
      }
    }
  }
}

.sheet-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
  margin-bottom: 20px;
}

.sheet-item {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: var(--el-color-primary);
  }
  
  &.current {
    background: var(--el-color-primary);
    color: white;
    border-color: var(--el-color-primary);
  }
  
  &.answered {
    background: var(--el-color-success-light-9);
    border-color: var(--el-color-success);
    color: var(--el-color-success);
  }
  
  &.marked {
    background: var(--el-color-warning-light-9);
    border-color: var(--el-color-warning);
    color: var(--el-color-warning);
  }
  
  &.answered.marked {
    background: linear-gradient(45deg, var(--el-color-success-light-9) 50%, var(--el-color-warning-light-9) 50%);
  }
}

.sheet-stats {
  .stat-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 12px;
    
    .stat-label {
      color: var(--el-text-color-secondary);
    }
    
    .stat-value {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }
}

.submit-content {
  .submit-warning {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 20px;
    padding: 12px;
    background: var(--el-color-warning-light-9);
    border-radius: 6px;
    color: var(--el-color-warning-dark-2);
  }
  
  .submit-stats {
    .stat-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      
      .unanswered-count {
        color: var(--el-color-danger);
        font-weight: 500;
      }
    }
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

@media (max-width: 1024px) {
  .exam-content {
    flex-direction: column;
  }
  
  .answer-sheet {
    width: 100%;
    margin: 0 16px 16px;
  }
  
  .sheet-grid {
    grid-template-columns: repeat(10, 1fr);
  }
}
</style>
